package com.strlst;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Main {

    private static void usage() {
        System.out.println("usage: ue0 host port matriculationNumber tuwelId");
        System.exit(1);
    }

    public static void main(String[] args) {
        // check arguments
        if (args.length < 4)
            usage();

        // fetch parameters
        var host = args[0];
        int port;
        try {
            port = Integer.parseInt(args[1]);
        } catch (NumberFormatException exception) {
            usage();
            // redundant, but the compiler is whining
            return;
        }
        var matriculationNumber = args[2];
        var tuwelId = args[3];

        try {
            // open tcp socket
            var socket = new Socket(host, port);
            var printWriter = new PrintWriter(socket.getOutputStream(), true);
            var bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // write request
            String requestString = String.format("!login %s %s", matriculationNumber, tuwelId);
            System.out.println(requestString);
            printWriter.println(requestString);

            // read response(s)
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

            // clean up resources
            bufferedReader.close();
            printWriter.close();
            socket.close();
        } catch (IOException exception) {
            System.err.println("an exception has occurred: " + exception.getMessage());
        }
    }
}
